import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { getLocation, getWeather, getCity, getAllWeather } from '@/api/index.js'

export const localStorageStore = defineStore('localStorage', () => {
  //城市名
  const cityName = ref('')
  //城市adcode
  const cityAdcode = ref('')
  //城市温度
  const cityTemp = ref([])
  //本地城市列表
  const cityList = ref([])

  // 获得温度数据,在每次主页访问时,根据本地存储的城市列表中的adcode,获取对应城市的气温数据
  const getTem = async (adcode) => {
    const res = await getWeather(adcode)
    if (res.status === 200) {
      return res.data.lives[0].temperature
    }
  }
  // 根据存储在本地的城市列表，获取当天气温
  const tempFunc = (data) => {
    data.value.forEach((item) => {
      getTem(item.adcode).then((res) => {
        cityTemp.value.push({
          adcode: item.adcode,
          tem: res
        })
      })
    })
  }
  //添加localStorage数据
  const addCity = (city, adcode, tem) => {
    console.log('addcity', city, adcode)
    cityList.value.push({
      city: city,
      adcode: adcode,
      isHover: false
    })
  }
  //删除localStorage数据,根据主视图渲染adcode
  const removeCity = (adcode) => {
    console.log('removeCity', adcode)
    const index = cityList.value.findIndex((item) => item.adcode === adcode)
    if (index !== -1) {
      cityList.value.splice(index, 1)
    }
  }
  //动态监听localStorage数据变化
  watch(
    cityList,
    (newVal) => {
      localStorage.setItem('cityList', JSON.stringify(newVal))
    },
    { deep: true }
  )

  //初始化localStorage数据
  const initCityList = () => {
    const cityListStr = localStorage.getItem('cityList')
    if (cityListStr) {
      cityList.value = JSON.parse(cityListStr)
    }
  }

  // 添加部分
  // 判断该城市是否已经存在于localStorage中
  const isCityExist = (adcode) => {
    return cityList.value.some((item) => item.adcode === adcode)
  }

  // HomeView部分
  // 定义数据
  // input获得数据集
  const inputGeocodes = ref([])
  // 错误信息
  const errorMessage = ref('')
  // input获得数据集方法
  const searchCityHomeview = async (name) => {
    // 判断输入是否为空
    if (name.trim() === '') {
      return
    }
    const result = await getCity(name)
    // 判断网络请求是否成功
    if (result.status !== 200) {
      console.log('获取失败(网络请求失败)')
      errorMessage.value = '对不起网络似乎除了点问题 请稍后再查询'
      inputGeocodes.value = []
      return
    }
    // 判断参数是否正确
    if (result.data.status === '1') {
      errorMessage.value = ''
      inputGeocodes.value = result.data.geocodes.map((item) => ({
        name: item.formatted_address,
        adcode: item.adcode
      }))
      cityName.value = inputGeocodes.value[0].name
      cityAdcode.value = inputGeocodes.value[0].adcode
      console.log('获取成功local', cityName.value, cityAdcode.value)
    } else {
      console.log('获取失败(参数错误)')
      errorMessage.value = '似乎没有找到你查找的城市'
      inputGeocodes.value = []
    }
  }

  // 路由部分
  const router = useRouter()
  // 点击事件,跳转路由
  const handleRouterChange = (name, adcode) => {
    router.push({ name: 'weather', params: { cityName: name }, query: { adcode: adcode } })
    console.log(name, adcode)
  }

  // 获得本地IP地址天气
  const locationWeather = ref('')
  const locationAllWeather = ref([])
  const getWeatherByIP = async () => {
    const result = await getLocation()
    if (result.status === 200) {
      const res = await getWeather(result.data.adcode)
      if (res.status === 200) {
        locationWeather.value = {
          city: res.data.lives[0].city,
          weather: res.data.lives[0].weather,
          tem: res.data.lives[0].temperature,
          winddirection: res.data.lives[0].winddirection,
          windpower: res.data.lives[0].windpower
        }
      }
    }
  }
  const getAllWeatherByIP = async () => {
    const result = await getLocation()
    if (result.status === 200) {
      const res = await getAllWeather(result.data.adcode)
      if (res.status === 200) {
        locationAllWeather.value = res.data.forecasts[0].casts
        console.log('天气数据加载完成')
      }
    }
  }

  // 天气详情页部分
  // 定义数据
  const forecasthWeatherData = ref([])
  const searchWeatherData = ref([])

  // 获取全部天气预报数据
  const getWeatherData = async (adcode) => {
    // 获取预报数据
    const res1 = await getAllWeather(adcode)
    forecasthWeatherData.value = res1.data.forecasts[0].casts
    // 获取当天数据
    const res2 = await getWeather(adcode)
    searchWeatherData.value = res2.data.lives
    console.log('1:', searchWeatherData.value, '2', forecasthWeatherData.value)
  }
  return {
    cityName,
    cityAdcode,
    cityList,
    inputGeocodes,
    errorMessage,
    locationWeather,
    locationAllWeather,
    forecasthWeatherData,
    searchWeatherData,
    cityTemp,
    getWeatherByIP,
    searchCityHomeview,
    handleRouterChange,
    addCity,
    removeCity,
    initCityList,
    isCityExist,
    getTem,
    getWeatherData,
    getAllWeatherByIP,
    tempFunc
  }
})
